package netty_chat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.ArrayList;
import java.util.List;

/**
 * 聊天室业务处理类
 */
public class NettyChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static List<Channel> channelList = new ArrayList<>();

    // 通道就绪事件
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 当有新的客户端连接的时候，将通道放入集合
        Channel channel = ctx.channel();
        channelList.add(channel);
        System.out.println("[Server]:" +
                channel.remoteAddress().toString().substring(1) + "上线.");
    }

    // 通道未就绪--channel下线
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 当有客户端断开连接的时候，就移除对应的通道
        Channel channel = ctx.channel();
        channelList.remove(channel);
        System.out.println("[Server]:" +
                channel.remoteAddress().toString().substring(1) + "下线.");
    }

    // 通道读取事件
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        // 当前发送消息的通道，当前发送的客户端连接
        Channel channel = ctx.channel();
        for (Channel ch : channelList) {
            if (ch != channel) { // 排除自身通道
                // channel和ChannelHandlerContext的writeAndFlush方法是同一个实现
                ch.writeAndFlush("[" +
                        channel.remoteAddress().toString().substring(1)
                        + "]说:" + msg);
            }
        }
    }

    // 异常处理事件
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        Channel channel = ctx.channel();
        channelList.remove(channel); // 移除集合
        System.out.println("[Server]:" +
                channel.remoteAddress().toString().substring(1) + "异常.");
    }
}
